package com.project.uitl;

import com.project.service.Servlet;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

public class AnnotationFactory {
    private static Map<String, Servlet> servletMap = new HashMap<>();

    static {
        File file = new File("lisserver\\src\\main\\java\\com\\project\\service");
        File[] files = file.listFiles();

        for (File f : files
        ) {
            if (f.isFile() && f.getName().endsWith(".java")) {
                String fileName = f.getName().substring(0, f.getName().length() - 5);
                String classPath = "com.project.service." + fileName;

                try {
                    Class c = Class.forName(classPath);
                    if (c.isAnnotationPresent(WebServlet.class)) {
                        WebServlet webServlet = (WebServlet) c.getAnnotation(WebServlet.class);
                        String url = webServlet.value();
                        servletMap.put(url, (Servlet) c.getConstructor().newInstance());
                    }
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static Servlet getServlet(String url) {
        return servletMap.get(url);
    }
}
